#include "multi_timer.h"

//静态全局变量：链表的头指针
static struct Timer* Shead_handle = NULL;
//静态全局变量：定时器计数值
static uint32_t Stimer_ticks = 0;

//struct Timer* handle 链表中一个节点的赋值 实例化
void timer_init(struct Timer* handle, void(*timeout_cb)(), uint32_t timeout, uint32_t repeat)
{
	handle->timeout_cb = timeout_cb;
	handle->timeout = Stimer_ticks + timeout;
	handle->repeat = repeat;
}

//节点插入到链表中 头插 其实头插就是2句话 前面遍历是防错
int timer_start(struct Timer* handle)
{
	struct Timer* target = Shead_handle;
	while(target) {
		if(target == handle) return -1;	//already exist.
		target = target->next;
	}
	handle->next = Shead_handle;
	Shead_handle = handle;
	return 0;
}

//节点从链表中移除 参考button中list.c 精彩的函数
void timer_stop(struct Timer* handle)
{
	struct Timer** curr;
	for(curr = &Shead_handle; *curr; ) 
	{
		struct Timer* entry = *curr;
		if (entry == handle) 
			*curr = entry->next;
		else
			curr  = &entry->next;
	}
}

// main loop.遍历链表 执行每个节点的业务逻辑 需要周期执行
void timer_loop()
{
	struct Timer* target;
	for(target=Shead_handle; target; target=target->next) 
	{
		if(Stimer_ticks >= target->timeout) 
		{
			if(target->repeat == 0)//如果是不需要重复的 那就是单次执行的 相当于延时函数 时间到了就结束该节点 
			{
				timer_stop(target);
			} else 
			{
				target->timeout = Stimer_ticks + target->repeat;//周而复始
			}
		target->timeout_cb();
		}
	}
}

//需要周期执行 更新时基
void timer_ticks()
{
	Stimer_ticks++;
}

